#pragma once
#include <iostream>
#include <string>
#include "Log.hpp"
#include "Init.hpp"

Log lg;

class Task
{
public:
    Task()
    {
    }
    Task(int sockfd, const std::string &ip, const uint16_t &port)
        : _sockfd(sockfd), _ip(ip), _port(port)
    {
    }
    void run()
    {
        char buffer[4096];
        Init init;
        ssize_t n = read(_sockfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client key# " << buffer << std::endl;
            std::string echo_string = init.translation(buffer);

            n = write(_sockfd, echo_string.c_str(), echo_string.size());
            if (n < 0)
            {
                lg(Warning, "write error, errno : %d, errstring: %s", errno, strerror(errno));
            }
        }
        else if (n == 0)
        {
            lg(Info, "%s:%d quit, server close sockfd: %d", _ip.c_str(), _port, _sockfd);
        }
        else
        {
            lg(Warning, "read error, sockfd: %d, client ip: %s, client port: %d", _sockfd, _ip.c_str(), _port);
        }
        close(_sockfd);
    }

    ~Task()
    {
    }

private:
    int _sockfd;
    std::string _ip;
    uint16_t _port;
};